import React from 'react';
import moment from 'moment';
import router from 'umi/router';
import Link from 'umi/link'

import { connect } from 'dva';

import { Card, Button,Form, Input, InputNumber, Select,DatePicker,Table } from 'antd';

const FormItem = Form.Item;

const { Option } = Select;

const linePath = '/AccountMove/AccountMove';
const formLinePath = '/AccountMove/AccountMoveFormLine';


@connect(({
  accountMoveForm,accountJournal
}) => ({
  accountMoveForm,accountJournal
}))
@Form.create()
class FormCreate extends React.Component {
  state = {
  }

  id = 0

  async componentDidMount() {
    const { location: {query: { id,fix } } } = this.props;
    //console.log(id, fix)

    const { dispatch } = this.props;

    if (id) {
      this.id = Number(id)
    }

    await dispatch({
        type: 'accountMoveForm/view2',
        payload:  { id:  this.id, fix }
    });


    await dispatch({
      type: 'accountJournal/search',
      payload: {domain:[] },
    });



  }

  treeview = [
      {
        title: '',
        dataIndex: '_',
        render: (_, { id }) => {
          return <Link to={`${formLinePath}?id=${id}`}>编辑</Link>;
        },
      },
      {
        title: '',
        dataIndex: '_del',
        render: (_, { id }) => {
          return <Button onClick={()=>this.handleDeleteLine(id)}>删除</Button>;
        },
      },
      { title: '摘要', dataIndex: 'name', },
      { title: '科目', dataIndex: 'account_id.name', },
      { title: '借方', dataIndex: 'debit', },
      { title: '贷方', dataIndex: 'credit', },
      { title: '业务伙伴', dataIndex: 'partner_id.name', },
      { title: '产品', dataIndex: 'product_id.name', },
      { title: '分析', dataIndex: 'analytic_account_id.name', },
      { title: '到期', dataIndex: 'date_maturity', },
  ]

  handleDeleteLine(id){
    //console.log(id)
    const { dispatch } = this.props;
    dispatch({
      type: 'accountMoveForm/formDeleteLine',
      payload: { id  },

    });

  }


  handleSubmit = e => {
    const { accountMoveForm:{formRecord}, dispatch, form } = this.props;
    e.preventDefault();


    const create_or_write = async (vals) => {
      if(this.id){
        //const { accountMoveForm: { error } } = this.props

        //console.log(error)

        //alert(11)

        await dispatch({
          type: 'accountMoveForm/write',
          payload : {
            id: this.id,  vals,
          },
        });

        //console.log('rettt', ret, error)

        router.push(`${linePath}?id=${this.id}`);
      }
      else{
        await dispatch({
          type: 'accountMoveForm/create',
          payload : {
            vals,
          },
        });

        const { accountMoveForm } = this.props;
        if (accountMoveForm.id){
          router.push(`${linePath}?id=${accountMoveForm.id}`);
        }
      }


    }


    form.validateFieldsAndScroll( async (err, values) => {
      if (!err) {
        const { date, number_cn } = values;
        const { line_ids } = formRecord;

        const vals = { ...values,
          date: date.format('YYYY-MM-DD'),
          line_ids: Object.values( line_ids ),
        };
        //console.log( vals );

        if(!number_cn){
          delete vals.number_cn;
        }

        await create_or_write(vals);

      }
    })
  }

  handleFieldChangeNumber(value, fieldName) {
    //console.log(fieldName, value);
    const data = {};

    if (fieldName === 'date'){
      data[fieldName] = value.format('YYYY-MM-DD');
    }
    else{
      data[fieldName] = value;
    }

    const { dispatch } = this.props;

    dispatch({
      type: 'accountMoveForm/formUpdate',
      payload: { ...data  },

    });

  }


  async handleFieldChange(e, fieldName ) {
    e.persist();
    //console.log(fieldName, e.target.value);
    const data = {};
    data[fieldName] = e.target.value;
    const { dispatch } = this.props;

    dispatch({
      type: 'accountMoveForm/formUpdate',
      payload: { ...data  },

    });

  }


  render() {
    const { form: { getFieldDecorator }  } = this.props;
    const { accountMoveForm: { displayRecord: record } } = this.props
    const { accountJournal: { recordsList: journalList } } = this.props;


    //console.log( record,formRecord)

    return (
      <div>
          <Form onSubmit={this.handleSubmit}
            onChange={this.onFieldsChange2}
          >
            <FormItem style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" >提交
              </Button>
            </FormItem>

            <FormItem label="日期">
              {getFieldDecorator('date', {
                rules: [{ required: true }],
                initialValue: record.date ? moment(record.date, 'YYYY-MM-DD') : moment()
               // initialValue: moment().format('YYYY-MM-DD')
               // initialValue: moment(record.date, 'YYYY-MM-DD'),
              })(<DatePicker onChange={e => this.handleFieldChangeNumber(e, 'date' )}/>)}
            </FormItem>


            <FormItem label="账簿">
              {getFieldDecorator('journal_id', {
                rules: [{ required: true }],
                initialValue: record.journal_id ? record.journal_id.id : 0
              })(
                <Select
                  placeholder="账簿"
                  onChange={e => this.handleFieldChangeNumber(e, 'journal_id')}
                >
                  <Option value={0} >未选择</Option>
                  {journalList.map(item => {
                    return (
                      <Option value={item.id} key="id">
                        {`${item.code} ${item.name}`}
                      </Option>
                    );
                  })}

                </Select>

              )}
            </FormItem>

            <FormItem label="凭证号">
              {getFieldDecorator('number_cn', {
                rules: [{ required: true }],
                initialValue: record.number_cn || 0,
              })(
                <InputNumber onChange={e => this.handleFieldChangeNumber(e, 'number_cn' )} />
              )}
            </FormItem>

            <FormItem label="摘要">
              {getFieldDecorator('ref', {
                rules: [{ required: true }],
                initialValue: record.ref || '.',
              })(
                <Input onChange={e => this.handleFieldChange(e, 'ref' )} />
              )}
            </FormItem>


          </Form>

          <Card title="明细行" bordered={false}>
            <Link to={formLinePath}>新增明细行</Link>
            <Table columns={this.treeview} dataSource={record.line_ids} rowKey="id" />
          </Card>

      </div>

    );
  }
}


export default FormCreate


